package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author zzyl
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto 所有信息
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //判断老人是否入住根据身份证号查询老人
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        Elder oldElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, idCardNo));
        if (ObjectUtils.isNotEmpty(oldElder)) {
            throw new RuntimeException("该老人已入住");
        }


        //走到这里就是为空,跟新床位状态,先查询床位是否为空根据床位id查询
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        // 保存或更新老人数据
        Elder elder = insertOrUpdateElder(bed, checkInApplyDto);


        // 新增签约办理
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        insertContract(contractNo, elder, checkInApplyDto);

        // 新增入住信息
        CheckIn checkIn = saveCheckIn(elder, checkInApplyDto);

      // 新增入住配置信息
      insertCheckInConfig(checkIn.getId(), checkInApplyDto);





    }
    // 新增入住配置信息
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {

        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    // 新增入住信息
    private CheckIn saveCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(Long.valueOf(elder.getId()));
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;

    }


    /**
     * 保存或新增老人
     */
    private Elder insertOrUpdateElder(Bed bed, CheckInApplyDto checkInApplyDto) {

        //拷贝信息

        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        Elder newElder = BeanUtil.toBean(checkInElderDto, Elder.class);

        newElder.setBedNumber(bed.getBedNumber());
        newElder.setBedId(bed.getId());
        newElder.setStatus(1);
        newElder.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        // 查询老人信息，（身份证号、状态不为1）
        Elder elderDb = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1));
        if (ObjectUtils.isNotEmpty(elderDb)) {
            // 修改
            elderMapper.updateById(newElder);
        } else {
            // 新增
            elderMapper.insert(newElder);
        }
        return newElder;
    }

    /**
     * 新增签约办理
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        // 属性拷贝
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);

    }


    @Override
    public CheckInDetailVo detail(Long id) {
        CheckIn checkIn = checkInMapper.selectById(id);

        //查询老人信息
        Elder elder = elderMapper.selectElderById(Math.toIntExact(checkIn.getElderId()));
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        //查询合同
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId()));
        //查询入住配置
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        BeanUtil.copyProperties(checkInConfig, checkInConfigVo);
        //转换家属列表:将string类型的json对象封装到list<ElderFamilyVo>
        List<ElderFamilyVo> elderFamilyVoList=(JSON.parseArray(elder.getRemark(), ElderFamilyVo.class));
        return new CheckInDetailVo(checkInElderVo,elderFamilyVoList,checkInConfigVo,contract);
        //String remark = elder.getRemark();

    }


}


